package uk.co.agileworks.bidpirate.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import uk.co.agileworks.bidpirate.model.Bid;
import uk.co.agileworks.bidpirate.model.User;

@Repository
public final class DAOImpl implements DAO {

	@Autowired
	private SessionFactory sessionFactory;

	@Transactional
	@Override
	public void deleteBid(Bid bid) {
		sessionFactory.getCurrentSession().delete(bid);
	}

	@Transactional(readOnly = true)
	@Override
	public Bid getBid(long id) {
		return (Bid) sessionFactory.getCurrentSession().get(Bid.class, id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	@Override
	public List<Bid> getBids(User user) {
		return sessionFactory.getCurrentSession()
				.createQuery("from Bid b where b.user=:user order by b.item.endTime")
				.setEntity("user", user).list();
	}

	@Transactional(readOnly = true)
	@Override
	public User getUser(String username) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery("from User where username=:username").setString("username", username)
				.uniqueResult();
	}

	@Transactional
	@Override
	public void saveOrUpdateBid(Bid bid) {
		sessionFactory.getCurrentSession().saveOrUpdate(bid);
	}

	@Transactional
	@Override
	public void saveOrUpdateUser(User user) {
		sessionFactory.getCurrentSession().saveOrUpdate(user);
	}
}
